<?php

/**
 * 卡系统接口类
 * @package  htdocs
 * @subpackage  module/base
 * @version 1.0
 */
interface cardInterface {

    /**
     * 查询卡生产单信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchCardProduct( &$arg_array );

    /**
     * 新增或修改卡生产单
     * @param array $arg_array 生产单数组
     * @return array
     */
    public function editCardProduct( $arg_array );

    /**
     * 审核卡生产单
     * @param int $productID 生产单ID
     * @return array
     */
    public function auditCardProduct( $productID );

    /**
     * 删除卡生产单
     * @param int $productID 生产单ID
     * @return array
     */
    public function delCardProduct( $productID );

    /**
     * 查询卡入库单信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchCardRKD( &$arg_array );

    /**
     * 新增或修改卡入库单
     * @param array $arg_array 入库单数组
     * @return array
     */
    public function editCardRKD( $arg_array );

    /**
     * 审核卡入库单
     * @param int $rkdID 入库单ID
     * @return array
     */
    public function auditCardRKD( $rkdID );

    /**
     * 删除卡入库单
     * @param int $rkdID 入库单ID
     * @return array
     */
    public function delCardRKD( $rkdID );

    /**
     * 查询卡申领单信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchCardApply( &$arg_array );

    /**
     * 新增或修改卡申领单
     * @param array $arg_array 申领单数组
     * @return array
     */
    public function editCardApply( $arg_array );

    /**
     * 删除卡申领单
     * @param int $applyID 申领单ID
     * @return array
     */
    public function delCardApply( $applyID );

    /**
     * 查询卡申领单详情表信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     */
    public function searchCardApplyDetail( &$arg_array );

    /**
     * 新增或修改申领单详情
     * @param array $arg_array 申领单数组
     * @return array
     */
    public function editCardApplyDetail( $arg_array );

    /**
     * 删除卡申领单详情
     * $uuid为空时删除该申领单下所有详情数据
     * $uuid不为空时只删除该条数据
     * @param int $applyID 申领单ID
     * @param string $uuid UUID【默认为空】【uuid是申领单详情表的主键】
     * @return array
     */
    public function delCardApplyDetail( $applyID, $uuid=null );

    /**
     * 卡申领单发卡
     * @param int $applyID 申领单ID
     * @return array
     */
    public function fkCardApply( $applyID );

    /**
     * 查询卡回款单信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *   'sortname' => string 排序字段
     *   'sortorder' => string 排序方式
     *   'page' => int 分页页码
     *   'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchCardHK( &$arg_array );

    /**
     * 新增或修改卡回款单
     * @param array $arg_array 回款单数组
     * @return array
     */
    public function editCardHK( $arg_array );

    /**
     * 审核卡回款单
     * @param int $hkID 回款单ID
     * @return array
     */
    public function auditCardHK( $hkID , $applyID );

    /**
     * 删除卡回款单
     * @param int $hkID 回款单ID
     * @return array
     */
    public function delCardHK( $hkID );

    /**
     * 查询卡申领单开票信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchCardInvoice( &$arg_array );

    /**
     * 新增或修改卡申领单开票信息
     * @param array $arg_array 申领单开票信息数组
     * @return array
     */
    public function editCardInvoice( $arg_array );

    /**
     * 审核卡申领单开票信息
     * @param string $invoiceID //发票ID
     * $applyID  //申请单号ID
     * @return array
     */
    public function auditCardInvoice( $invoiceID , $applyID );

    /**
     * 删除卡申领单开票信息
     * @param string $uuid UUID
     * @return array
     */
    public function delCardInvoice( $uuid );

    /**
     * 卡申领单开票信息 -- 冲红
     * @param string $uuid UUID
     * @return array
     */
    public function chCardInvoice( $uuid );

    /**
     * 修改卡系统卡状态(回滚代金卡状态)
     * @param int $cardID 卡号
     * @return array
     */
    public function changeCardStat( $cardID );

    /**
     * 批量作废代金卡
     * @param array $card_array 卡号数组
     * $card_array = array(
     *      0 => '卡号',
     *      1 => '卡号',
     *      ...
     * );
     * @return array
     */
    public function batchChangeCardStat( $card_array );

}


/**
 * 卡系统操作类
 * @package  htdocs
 * @subpackage  module/base
 * @version 1.0
 */

class cardHandler implements cardInterface {

    private $dbca;

    public function __construct( &$dbca ) {
        $this->dbca = $dbca;
    }

    /**
     * 生产单查询
     * $arg_array = array (
                            'productID' => int 生产单ID
                            'cardType' => int  卡类型
                            'site_id' => int 站点ID
                            'startDate' => string 开始时间
                            'endDate' => string 结束时间
                            'sortname' => string 排序字段
                            'sortorder' => string 排序方式
                            'page' => int 分页页码
                            'rp' => int 分页页数
                          )
     */
    public function searchCardProduct( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //代金卡名称
        if( isset($arg_array['cardName']) &&  !empty($arg_array['cardName']) ){
            $sql .= ' AND cardName like ?';
            $params_type .= 's';
            $params_array[] = '%'.$arg_array['cardName'].'%';
        }

        //卡面值ID
        if ( isset($arg_array['faceValueID']) && is_numeric($arg_array['faceValueID']) ) {
            $sql .= ' AND faceValueID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['faceValueID'];
        }

        //卡类型
        if ( isset($arg_array['cardType']) && is_numeric($arg_array['cardType']) ) {
            $sql .= ' AND cardType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cardType'];
        }

        //生产单ID
        if ( isset($arg_array['productID']) && is_numeric($arg_array['productID']) ) {
            $sql .= ' AND productID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['productID'];
        }

        //开始时间和结束时间
        if( !empty($arg_array['startDate']) && !empty($arg_array['endDate']) ){
            $sql .= ' AND startDate >= ? AND  endDate <= ? ';
            $params_type .='ss';
            $params_array[] = $arg_array['startDate'];
            $params_array[] = $arg_array['endDate'];
        }

        //卡状态
        if ( isset($arg_array['status']) && in_array( $arg_array['status'] , array(1,2,3) ) ) {
            $sql .= ' AND status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['status'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_product ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询代金卡生产单信息
            $search_sql = 'SELECT * FROM card_product ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'productID' => $item->productID,
                    'cardName' => $item->cardName,
                    'faceValueID' => $item->faceValueID,
                    'faceValue' => $item->faceValue,
                    'cardNumber' => $item->cardNumber,
                    'useNumber' => $item->useNumber,
                    'startDate' => $item->startDate,
                    'status' => $item->status,
                    'endDate' => $item->endDate,
                    'cardType' => $item->cardType,
                    'goodsSelector' => $item->goodsSelector,
                    'remark' => $item->remark
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }

    /**
     * 新增或修改卡生产单
     * @param array $arg_array 生产单数组
     * @return array
     * @throws Exception
     */
    public function editCardProduct( $arg_array ) {

        //检查参数是否完整
        if(!isset($arg_array['cardNumber'],$arg_array['faceValueID'],$arg_array['cardType'],$arg_array['useNumber'],$arg_array['operator'],$arg_array['cardName'],$arg_array['startDate'],$arg_array['endDate'])){
            return array( 'code'=>400 , 'message'=>'参数错误，请与管理员联系' );
        }

        //连接错误信息的字符串
        $error_msg = '';

        $cardName= trim($arg_array['cardName']);
        if(empty($cardName)){
            $error_msg .= '代金卡名称不能为空<br>';
        }

        $cardType = $arg_array['cardType'];
        if( empty($cardType) ){
            $error_msg .= '代金卡类型不能为空<br>';
        }else{
            if( !in_array( $cardType , array(1,2,3) ) )
                $error_msg .= '代金卡类型有误<br>';
        }


        $cardNumber = trim($arg_array['cardNumber']);
        if(empty($cardNumber)){
            $error_msg .= '卡张数不能为空<br>';
        }
        if(!is_numeric($cardNumber) || $cardNumber<=0){
            $error_msg .= '卡张数只能为数字且必须大于0<br>';
        }

        $useNumber = trim($arg_array['useNumber']);
        if( !is_numeric($useNumber) ){
            $error_msg .= '可使用次数不能为空且必须为数字<br>';
        }

        $startDate = trim($arg_array['startDate']);
        $endDate = trim($arg_array['endDate']);

        if(empty($startDate) || empty($endDate)){
            $error_msg .= '开始时间和结束时间不能为空<br>';
        }

        if($startDate>$endDate){
            $error_msg .= '开始时间不能大于结束时间<br>';
        }

        if( $error_msg != '' )
            return array( 'code'=>400 , 'message'=>$error_msg );

        $goodsSelector = trim($arg_array['goodsSelector']);
        $remark = htmlspecialchars( trim($arg_array['remark']) );
        $productID = isset($arg_array['productID']) ? trim($arg_array['productID']) : null;

        //查询代金卡面值信息
        $searchCardType = 'SELECT * FROM sys_item WHERE itemID = ? AND itemCategoryID = ?';
        $cardTypeName   = $this->dbca->stmt_query( $searchCardType , 'ii' , array($arg_array['faceValueID'],10) );

        if( empty($cardTypeName) )
            return array( 'code'=>404 , 'message'=>'没有找到面值信息' );

        try{

            //事务开启
            $this->dbca->beginTransaction();

            $card_product = new entity('card_product');

            if( $productID ){

                $card_product->productID = $productID;
                if( !$this->dbca->fetch($card_product) )
                    throw new Exception( '没有找到生产单信息' , 404 );

                if( $card_product->status != 1 )
                    throw new Exception( '该代金卡已通过审核，不可修改' , 400 );

            }else{

                $card_product->creator = $arg_array['operator'];

            }

            $card_product->cardName = $cardName;
            $card_product->faceValueID = $arg_array['faceValueID'];
            $card_product->faceValue = $cardTypeName[0]->itemName;
            $card_product->cardType = $cardType;
            $card_product->cardNumber  = $cardNumber;
            $card_product->useNumber = $useNumber;
            $card_product->goodsSelector = $goodsSelector;
            $card_product->remark = $remark;
            $card_product->startDate = $startDate;
            $card_product->endDate = $endDate;
            $card_product->status = 1;

            //保存代金卡生产单
            $this->dbca->save($card_product);

            //提交事务
            $this->dbca->commit();

            if( $productID ){
                return array( 'code'=>200 , 'message'=>'代金卡更新成功');
            }else{
                return array( 'code'=>200 , 'message'=>'代金卡添加成功');
            }

        }catch(Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            }else{

                error_log($e->getMessage());
                return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );

            }

        }

    }

    /**
     * 审核卡生产单
     * @param int $productID 生产单ID
     * @return array
     * @throws Exception
     */
    public function auditCardProduct( $productID ) {

        if( !is_numeric($productID) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        /**
         * 代金卡生产单状态：1:待审核   2：生产   3:入库
         */

        //查询生产单信息
        $card_product = new entity('card_product');
        $card_product->productID = $productID;

        if( !$this->dbca->fetch( $card_product ) )
            return array( 'code'=>404 , 'message'=>'没有找到代金卡信息' );

        if( $card_product->status != 1 )
            return array( 'code'=>404 , 'message'=>'您当前页面已过期，请刷新页面' );

        //组装数组
        $params[] = $productID;
        $params[] = $card_product->cardNumber;
        $params[] = date('Ymd');

        //组装传参数组
        $globalArr['action'] = 'card';
        $globalArr['operFlg'] = 1;
        $globalArr['params'] = $params;

        try{

            //调用生产卡数据方法
            $returnMsg = sendMessageMq( $globalArr , 3 );

            return array( 'code'=>200 , 'message'=>'审核成功' );

        }catch (Exception $e){
            error_log($e->getMessage());
            return array( 'code'=>500 , 'message'=>'系统错误，审核失败' );
        }

    }

    /**
     * 删除卡生产单
     * @param $arg_array 生产单ID组成的数组，例如：
     * $arg_array = Array(
                            [0] => 19
                            [1] => 18
                            [2] => 17
                          ）
     * @return array
     * @throws Exception
     */
    public function delCardProduct( $arg_array ) {

        /**
         * 代金卡生产单状态：1:待审核   2：生产   3:入库
         */

        //统计不存在的代金卡生产单的数目
        $errorNum = 0;

        //统计已经审核过的生产单数目
        $cardAudited = 0;

        //记录要删除的entity对象
        $deleteObjArr = array();

        if( empty($arg_array) )
            return array(  'code'=>400 , 'message'=>'请选择要删除的代金卡' );

        //检查要删除的所有代金卡
        foreach( $arg_array as $productID ){

            //检查代金卡生产单信息是否存在
            $check_obj = new entity('card_product');
            $check_obj->productID = $productID;

            if( !$this->dbca->fetch( $check_obj ) )
                $errorNum++;  //记录不存在的代金卡生产单数量

            if( $check_obj->status != 1 )
                $cardAudited++;  //记录已经审核过的代金卡生产单数量

            $deleteObjArr[] = $check_obj;

        }

        if( $errorNum > 0 ){

            return array(  'code'=>400 , 'message'=>'所选部分信息已不存在，请刷新页面' );

        }

        if( $cardAudited > 0 ){

            return array(  'code'=>400 , 'message'=>'已审核的代金卡不可删除' );

        }


        try{

            //开启事务
            $this->dbca->beginTransaction();

            //循环删除
            foreach( $deleteObjArr as $delobj ){

                $this->dbca->delete( $delobj );

            }

            //提交事务
            $this->dbca->commit();

            return array('message'=>'删除成功', 'code'=>200);

        }catch( Exception $e ){

            //提交事务
            $this->dbca->rollBack();

            error_log($e->getMessage());
            return array('message'=>'系统错误，请与管理员联系', 'code'=>500);

        }

    }

    /**
     * 查询代金卡详情
     * @param array $arg_array
     *  $arg_array = array (
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     */
    public function searchCardDetail( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //卡号
        if ( isset($arg_array['cardID']) && is_numeric($arg_array['cardID']) ) {
            $sql .= ' AND cardID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cardID'];
        }

        //生产单ID
        if ( isset($arg_array['productID']) && is_numeric($arg_array['productID']) ) {
            $sql .= ' AND productID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['productID'];
        }

        //入库单ID
        if ( isset($arg_array['rkdID']) && is_numeric($arg_array['rkdID']) ) {
            $sql .= ' AND rkdID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['rkdID'];
        }

        //申领单ID
        if ( isset($arg_array['applyID']) && is_numeric($arg_array['applyID']) ) {
            $sql .= ' AND applyID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['applyID'];
        }

        //卡面值ID
        if ( isset($arg_array['faceValueID']) && is_numeric($arg_array['faceValueID']) ) {
            $sql .= ' AND faceValueID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['faceValueID'];
        }

        //卡状态
        if ( isset($arg_array['cardStatus']) && in_array( $arg_array['cardStatus'] , array(1,2,3,4,5,6,7) ) ) {
            $sql .= ' AND cardStatus = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cardStatus'];
        }

        //卡类型
        if ( isset($arg_array['cardType']) && in_array( $arg_array['cardType'] , array(1,2,3) ) ) {
            $sql .= ' AND cardType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cardType'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_detail ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询代金卡入库单信息
            $search_sql = 'SELECT * FROM card_detail ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'cardID' => $item->cardID,
                    'cardPwd' => $item->cardPwd,
                    'productID' => $item->productID,
                    'rkdID' => $item->rkdID,
                    'applyID' => $item->applyID,
                    'cardType' => $item->cardType,
                    'faceValueID' => $item->faceValueID,
                    'faceValue' => $item->faceValue,
                    'discount' => $item->discount,
                    'cardStatus' => $item->cardStatus,
                    'useNumber' => $item->useNumber,
                    'usedNumber' => $item->usedNumber,
                    'goodSelector' => $item->goodSelector,
                    'sendCardTime' => $item->sendCardTime,
                    'startDate' => $item->startDate,
                    'endDate' => $item->endDate,
                    'externalNo' => $item->externalNo
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询卡入库单信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchCardRKD( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //入库单ID
        if ( isset($arg_array['rkdID']) && is_numeric($arg_array['rkdID']) ) {
            $sql .= ' AND rkdID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['rkdID'];
        }

        //生产单ID
        if ( isset($arg_array['productID']) && is_numeric($arg_array['productID']) ) {
            $sql .= ' AND productID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['productID'];
        }

        //入库状态
        if ( isset($arg_array['status']) && in_array( $arg_array['status'] , array(0,1) ) ) {
            $sql .= ' AND status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['status'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_rkd ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询代金卡入库单信息
            $search_sql = 'SELECT * FROM card_rkd ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'rkdID' => $item->rkdID,
                    'productID' => $item->productID,
                    'startID' => $item->startID,
                    'endID' => $item->endID,
                    'status' => $item->status,
                    'remark' => $item->remark
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }

    /**
     * 新增或修改卡入库单
     * @param array $arg_array 入库单数组
     * @return array
     * @throws Exception
     */
    public function editCardRKD( $arg_array ) {

        if(!isset($arg_array['startID'],$arg_array['endID'],$arg_array['productID'])){
            return array( 'code'=>400 , 'message'=>'参数错误，请与管理员联系' );
        }

        //区别保存、编辑标志
        $saveFlg = 1;

        //连接错误信息字符串
        $error_msg = '';

        $startID = trim($arg_array['startID']);

        if( empty($startID) ){
            $error_msg .= '起始编号不能为空<br>';
        }

        $endID = trim($arg_array['endID']);
        if( empty($endID) ){
            $error_msg .= '结束编号不能为空<br>';
        }

        $productID = trim($arg_array['productID']);
        if(empty($productID)){
            $error_msg .= '生产单号不能为空<br>';
        }

        if( $error_msg != '' )
            return array( 'code'=>400 , 'message'=>$error_msg );

        $rkdID = isset($arg_array['rkdID']) ? trim($arg_array['rkdID']) : null;

        /**
         * 编辑时，将代金卡详情表中属于该入库单ID下的代金卡全部重置为“已生产”状态
         * 注：考虑到编辑时，有可能改变了该入库单下的代金卡的起始编号
         */
        if( !empty($rkdID) ){
            $this->dbca->stmt_query('UPDATE card_detail SET cardStatus=?,rkdID=? WHERE rkdID=?' , 'iii' , array(1,NULL,$rkdID) );
        }

        //查询选择的起止编号代金卡是否已经全部被占用
        $check_card_range = 'SELECT COUNT(*) total FROM card_detail WHERE cardStatus=1 AND cardID BETWEEN ? AND ?';
        $cnt_result = $this->dbca->stmt_query($check_card_range,'ii',array($startID,$endID));

        //如没有查到该范围内“已生产”的代金卡，则说明该范围内的代金卡已经全部被占用
        if($cnt_result[0]->total == 0)
            return array( 'code'=>404 , 'message'=>'代金卡起始编号'.$startID.'~'.$endID.'不存在' );

        //查询该范围内的代金卡是否存在
        $check_card_exist = 'SELECT cardID,cardStatus,cardType FROM card_detail WHERE cardID BETWEEN ? AND ? AND cardStatus=1';
        $result = $this->dbca->stmt_query( $check_card_exist , 'ii' , $startID,$endID );
        if( empty($result) )
            return array( 'code'=>404 , 'message'=>'没有找到该范围内代金卡信息' );

        foreach($result as $value){
            $cardNo_arr[] = $value->cardID; //记录所选范围内可以入库的代金卡
        }

        //保存不符合条件的卡号
        $str = '';

        //记录不能使用的卡的张数
        $cannotUse = 0;

        for($i=$startID;$i<=$endID;$i++){
            if(!in_array($i,$cardNo_arr)){
                $str .= '['.$i.']';
                $cannotUse++;
            }
        }

        if( $cannotUse > 10 )
            return array( 'code'=>400 , 'message'=>'您输入的代金卡起始编号中至少有10张不能入库，请检查代金卡' );

        if( $str != '' )
            return array( 'code'=>400 , 'message'=>'代金卡卡号'.$str.'不能被申请，请重新输入代金卡起始编号' );

        try{

            //事务开启
            $this->dbca->beginTransaction();

            $card_insert = new entity('card_rkd');

            if( $rkdID ){

                $card_insert->rkdID = $rkdID;
                if( !$this->dbca->fetch($card_insert) )
                    throw new Exception('没有找到入库单信息' , 404);

                if( $card_insert->status == 1 )
                    throw new Exception('该入库单中的代金卡已入库,不可修改' , 400);

                $saveFlg = 2;

            }else{
                $card_insert->creator = $arg_array['operator'];
                $card_insert->remark = $arg_array['remark'];
            }

            $card_insert->productID = $productID;
            $card_insert->startID = $startID;
            $card_insert->endID = $endID;
            $card_insert->status = 0;


            $this->dbca->save($card_insert);

            if( empty($rkdID) )
                $rkdID = $this->dbca->insert_id;

            //更新代金卡状态为代金卡入库申请中
            $sqlstr = 'update card_detail set cardstatus=?,timeStamp=?,rkdID=? WHERE cardID BETWEEN ? AND ?';
            $this->dbca->stmt_query( $sqlstr , 'isiii' , array( 2 , date('Y-m-d H:i:s') , $rkdID , $startID , $endID) );

            //提交事务
            $this->dbca->commit();

            if( $saveFlg == 2 ){
                return array( 'code'=>200 , 'message'=>'入库单更新成功' );
            }else{
                return array( 'code'=>200 , 'message'=>'入库单添加成功' );
            }

        }catch(Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            }else{

                error_log($e->getMessage());
                return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );

            }

        }

    }

    /**
     * 审核卡入库单
     * @param int $rkdID 入库单ID
     * @return array
     * @throws Exception
     */
    public function auditCardRKD( $rkdID ) {

        if( !is_numeric($rkdID) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        /**
         * 代金卡入库单状态：0:待审核   1:已入库
         */

        //查询生产单信息
        $card_rkd = new entity('card_rkd');
        $card_rkd->rkdID = $rkdID;

        if( !$this->dbca->fetch( $card_rkd ) )
            return array( 'code'=>404 , 'message'=>'没有找到入库单信息' );

        if( $card_rkd->status != 0 )
            return array( 'code'=>404 , 'message'=>'您当前页面已过期，请刷新页面' );

        $card_rkd->status = 1;

        try{

            //事务开启
            $this->dbca->beginTransaction();

            $this->dbca->save($card_rkd);

            //同时将该入库单中的代金卡状态置为“已入库”
            $this->dbca->stmt_query( 'UPDATE card_detail SET cardStatus = ? WHERE rkdID = ?' , 'ii' , array(3,$rkdID) );

            //事务提交
            $this->dbca->commit();

            return array( 'code'=>200 , 'message'=>'审核成功' );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            error_log($e->getMessage());
            return array( 'code'=>500 , 'message'=>'系统错误，审核失败' );
        }

    }

    /**
     * 删除卡入库单
     * @param $arg_array 入库单ID组成的数组，例如：
     * $arg_array = Array(
                            [0] => 19
                            [1] => 18
                            [2] => 17
                        ）
     * @return array
     * @throws Exception
     */
    public function delCardRKD( $arg_array ) {

        /**
         * 代金卡状态：1.已生产  2.入库申请  3.已入库  4.申领申请  5.发卡  6.已使用  7.已作废
         */

        //统计不存在的入库单的数目
        $errorNum = 0;

        //统计已经审核过的入库单数目
        $rkdAudited = 0;

        //记录要删除的entity对象
        $deleteObjArr = array();

        if( empty($arg_array) )
            return array(  'code'=>400 , 'message'=>'请选择要删除的入库单' );

        //检查要删除的所有入库单
        foreach( $arg_array as $rkdID ){

            //检查入库单信息是否存在
            $check_obj = new entity('card_rkd');
            $check_obj->rkdID = $rkdID;

            if( !$this->dbca->fetch( $check_obj ) )
                $errorNum++;  //记录不存在的入库单数量

            if( $check_obj->status != 0 )
                $rkdAudited++;  //记录已经审核过的入库单数量

            $deleteObjArr[$rkdID] = $check_obj;

        }

        if( $errorNum > 0 ){

            return array(  'code'=>400 , 'message'=>'所选部分信息已不存在，请刷新页面' );

        }

        if( $rkdAudited > 0 ){

            return array(  'code'=>400 , 'message'=>'已审核的入库单不可删除' );

        }


        try{

            //开启事务
            $this->dbca->beginTransaction();

            //循环删除
            foreach( $deleteObjArr as $rkdID=>$delobj ){

                //删除入库单信息
                $this->dbca->delete( $delobj );

               //将该入库单下的所有代金卡的状态重置为“已生产”并重置入库单号
                $this->dbca->stmt_query( 'UPDATE card_detail SET cardStatus = ?,rkdID = ? WHERE rkdID = ?' , 'iii' , array(1,NULL,$rkdID) );

            }

            //提交事务
            $this->dbca->commit();

            return array('message'=>'删除成功', 'code'=>200);

        }catch( Exception $e ){

            //提交事务
            $this->dbca->rollBack();

            error_log($e->getMessage());
            return array('message'=>'系统错误，请与管理员联系', 'code'=>500);

        }

    }

    /**
     * 查询卡申领单信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchCardApply( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //申领单号
        if ( isset($arg_array['applyID']) && is_numeric($arg_array['applyID']) ) {
            $sql .= ' AND applyID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['applyID'];
        }

        //申领人
        if ( isset($arg_array['applyPerson']) && is_numeric($arg_array['applyPerson']) ) {
            $sql .= ' AND applyPerson = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['applyPerson'];
        }

        //客户类型
        if ( isset($arg_array['custType']) && in_array( $arg_array['custType'] , array(0,1) ) ) {
            $sql .= ' AND custType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['custType'];
        }

        //联系手机或电话
        if ( isset($arg_array['connectway']) && !empty($arg_array['connectway']) ) {
            $sql .= ' AND connectway = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['connectway'];
        }

        //申请状态
        if ( isset($arg_array['status']) && in_array( $arg_array['status'] , array(1,2,3) ) ) {
            $sql .= ' AND status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['status'];
        }

        //申请时间
        if ( !empty( $arg_array['startDate'] ) && !empty($arg_array['endDate']) ) {
            $sql .= ' AND applyTime >= ? AND applyTime <= ?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'];
            $params_array[] = $arg_array['endDate'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_apply ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询代金卡申领单信息
            $search_sql = 'SELECT * FROM card_apply ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'applyID' => $item->applyID,
                    'applyPerson' => $item->applyPerson,
                    'applyTime' => $item->applyTime,
                    'custType' => $item->custType,
                    'custname' => $item->custname,
                    'paymentName' => $item->paymentName,
                    'connectname' => $item->connectname,
                    'connectway' => $item->connectway,
                    'totalAmount' => $item->totalAmount,
                    'totalNumber' => $item->totalNumber,
                    'status' => $item->status,
                    'sendCardTime' => $item->sendCardTime,
                    'externalNo' => $item->externalNo
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 新增或修改卡申领单
     * @param array $arg_array 申领单数组
     * @return array
     * @throws Exception
     */
    public function editCardApply( $arg_array ) {

        if( !isset($arg_array['custType'],$arg_array['custname'],$arg_array['connectname'],$arg_array['connectway'],$arg_array['applyPerson'],$arg_array['applyTime']) ){
           return array( 'code'=>400 , 'message'=>'参数错误' );
        }

        //区别编辑、保存的标志
        $saveFlg = 1;

        //连接错误信息
        $error_msg = '';

        $custType = trim($arg_array['custType']);
        if( !in_array( $custType , array(0,1) ) )
            $error_msg .= '客户类型不能为空<br>';

        $custname = trim($arg_array['custname']);
        if( empty($custname) )
            $error_msg .= '客户名称不能为空<br>';

        $connectname = trim($arg_array['connectname']);
        if( empty($connectname) )
            $error_msg .= '联系人不能为空<br>';

        $connectway = trim($arg_array['connectway']);
        if(empty($connectway))
            $error_msg .= '联系方式不能为空<br>';

        $applyPerson= trim($arg_array['applyPerson']);
        if(empty($applyPerson))
            $error_msg .= '申请人不能为空<br>';

        $applyTime = $arg_array['applyTime'];
        if(empty($applyTime))
            $error_msg .= '申请时间不能为空<br>';

        if( empty( $arg_array['cardInfo'] ) )
            $error_msg .= '请添加申领的代金卡<br>';

        if( $error_msg != '' )
            return array( 'code'=>400 , 'message'=>$error_msg );

        $applyID = isset( $arg_array['applyID'] ) ? $arg_array['applyID'] : NULL;

        try{

            //事务开启
            $this->dbca->beginTransaction();

            $card_apply_save = new entity('card_apply');

            if( $applyID ){

                $saveFlg = 2;

                $card_apply_save->applyID = $applyID;
                if( !$this->dbca->fetch($card_apply_save) )
                    throw new Exception('没有找到申请单信息' , 404);

                if( $card_apply_save->status != 1 )
                    throw new Exception('该申请单已发卡，不可修改' , 400);

                //修改时先将申领单详情表中的数据删除
                $sql_delete = 'DELETE FROM card_apply_detail WHERE applyID=?';
                $this->dbca->stmt_query( $sql_delete , 'i' , $applyID );

                //将该申领单中的所有卡状态重置为“已入库”
                $sqlCardDetail = 'UPDATE card_detail SET cardStatus=?,applyID=? WHERE applyID=?';
                $this->dbca->stmt_query( $sqlCardDetail , 'isi' , array(3,NULL,$applyID) );

            }else{

                $card_apply_save->applyID = $arg_array['operator'];

            }

            $card_apply_save->totalAmount = $arg_array['totalAmount'];
            $card_apply_save->totalNumber = $arg_array['totalNumber'];
            $card_apply_save->applyPerson = $arg_array['applyPerson'];
            $card_apply_save->applyTime = $applyTime;
            $card_apply_save->custType = $custType;
            $card_apply_save->custname = $custname;
            $card_apply_save->connectname = $connectname;
            $card_apply_save->connectway = $connectway;
            $card_apply_save->status  = 1;

            $this->dbca->save($card_apply_save);

            if( empty($applyID) )
                $applyID = $this->dbca->insert_id;  //获取刚刚保存进数据库的ID


            foreach( $arg_array['cardInfo'] as $apply_detail ){

                $card_apply_detail_save = new entity('card_apply_detail');
                $card_apply_detail_save->applyID = $applyID;
                $card_apply_detail_save->productID = $apply_detail['productID'];
                $card_apply_detail_save->faceValue = $apply_detail['faceValue'];
                $card_apply_detail_save->startID = $apply_detail['startID'];
                $card_apply_detail_save->endID = $apply_detail['endID'];
                $card_apply_detail_save->cardNumber = $apply_detail['cardNumber'];
                $card_apply_detail_save->discount = $apply_detail['discount'];
                $card_apply_detail_save->totalAmount = $apply_detail['totalAmount'];
                $this->dbca->save($card_apply_detail_save);

                //将代金卡详情表中的对应的卡状态设置为“申领申请”
                $sqlChangeCardDetail = 'UPDATE card_detail SET cardStatus=?,applyID=?,timeStamp=? where cardID between ? and ?';
                $typeChangeCardDetail = 'issii';
                $paramChangeCardDetail = array( 4 , $applyID , date('Y-m-d H:i:s') , $apply_detail['startID'] , $apply_detail['endID'] );
                $this->dbca->stmt_query($sqlChangeCardDetail,$typeChangeCardDetail,$paramChangeCardDetail);

            }

            //提交事务
            $this->dbca->commit();

            if( $saveFlg == 2 ){
                return array( 'code'=>200 , 'message'=>'申领单更新成功' , 'data'=>$applyID );
            }else{
                return array( 'code'=>200 , 'message'=>'申领单添加成功' , 'data'=>$applyID );
            }

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){
                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );
            }else{
                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );
            }

        }

    }

    /**
     *代金卡检查
     * param :$arg_array 要检测数据 ，$flg 检测流程控制开关($flg=1表示进入编辑流程),$_hiddStartID、$_hiddEndID原始startID、endID
     * @return unknown
     */
    public function checkCard($arg_array){

        if(!isset($arg_array['startID'],$arg_array['endID'])){
            return array( 'code'=>400 , 'message'=>'参数错误，请联系网站管理员' );
        };

        //接收参数
        $flg = isset($arg_array['flg'])?$arg_array['flg']:NULL;
        $_hiddStartID = isset($arg_array['hiddStartID'])?$arg_array['hiddStartID']:NULL;
        $_hiddEndID = isset($arg_array['hiddEndID'])?$arg_array['hiddEndID']:NULL;

        //连接错误信息
        $error_msg = '';

        $cardNumber = trim($arg_array['cardNumber']);
        if(empty($cardNumber) || !is_numeric($cardNumber)){
            $error_msg .= '代金卡张数不能为空且只能为数字<br>';
        }

        $startID = trim($arg_array['startID']);
        $endID = trim($arg_array['endID']);
        $productID = trim($arg_array['productID']);

        if(empty($startID) || empty($endID) || !is_numeric($startID) || !is_numeric($endID)){
            $error_msg .= '代金卡起止编号不能为空且必须为数字<br>';
        }

        if( $endID-$startID != $cardNumber-1 ){
            $error_msg .= '结束编号减去初始编号和所选张数不相符，请重填写<br>';
        }

        if( $error_msg != '' )
            return array( 'code'=>400 , 'message'=>$error_msg );

        $sql ='SELECT count(*) total FROM card_detail WHERE cardStatus=? and productID=?';
        $result = $this->dbca->stmt_query($sql,'is',array(3,$productID));

        if($result[0]->total == 0)
            return array( 'code'=>400 , 'message'=>'没有找到该面值处于入库的代金卡' );

        //$flg != 1 则是新增状态，此时只需判断传入的startID、endID、cardType范围内对应的cardID的cardStatus是否为3
        if ( empty($flg) ){

            //查询出该生产单中此号段内处于“入库”状态的代金卡数量
            $sqlCountCard = 'SELECT COUNT(*) allcard FROM card_detail WHERE cardID BETWEEN ? AND ? AND cardStatus=? AND productID=?';
            $typeCountCard = 'iiii';
            $paremCountCard = array($startID,$endID,3,$productID);
            $resultCountCard = $this->dbca->stmt_query($sqlCountCard,$typeCountCard,$paremCountCard);

            //如果全部符合条件则返回true,其他都返回false，并返回错误号段提示
            if ( !empty($resultCountCard) && $resultCountCard[0]->allcard == $cardNumber ){

                return array( 'code'=>200 , 'message'=>'此号段代金卡可用' , 'data'=>$arg_array );

            }elseif ( $resultCountCard[0]->allcard == 0 ){

                return array( 'code'=>400 , 'message'=> '该代金卡以下范围内无可被申领的代金卡:['.$startID.']～['.$endID.']' );

            }else{

                //查询出该生产单中此号段内处于“入库”状态的代金卡卡号
                $sql = 'SELECT cardID FROM card_detail WHERE cardID BETWEEN ? AND ? AND cardStatus=? AND productID=?';
                $result = $this->dbca->stmt_query( $sql , 'iiii' , array($startID,$endID,3,$productID) );

                //记录入库状态的所有卡号
                $arr_canbe = array();

                if ( !empty($result) ){
                    foreach ($result as $value){
                        $arr_canbe[]=$value->cardNo;
                    }
                }

                //分解选择的卡号段为数组
                $card_arr = range( $startID , $endID );

                //记录不可用的卡号
                $str = '';

                foreach($card_arr as $line){
                    if(!in_array($line,$arr_canbe)){
                        $str .= '['.$line.']';
                    }
                }

                if( !empty($str) ){

                    $arr = explode('][', $str);
                    if (count($arr) > 10){
                        $arr = array_slice($arr, 0, 9);
                        $str = implode('][', $arr);
                        $str .= ']......';

                        return array( 'code'=>400 , 'message'=>'该代金卡以下范围内卡号不存在或已被申请:'.$str );

                    }else {

                        $str = implode('][', $arr);
                        $str .= ']';
                        return array( 'code'=>400 , 'message'=>'该代金卡以下范围内卡号不存在或已被申请:'.$str );

                    }

                }
            }

        }else {

            //获取原有的起止编号
            if (empty($_hiddStartID) || empty($_hiddEndID)){

                return array( 'code'=>400 , 'message'=>'参数错误' );

            }else {

                if ($startID >= $_hiddStartID && $endID <= $_hiddEndID){

//                    $this->returnBack($_hiddStartID,$_hiddEndID);
                    return array( 'code'=>200 , 'message'=>'此号段可用' , 'data'=>$arg_array );

                }else{

                    $sqlCount = 'SELECT COUNT(*) AS allCount FROM card_detail WHERE cardID BETWEEN ? AND ? AND cardStatus=3 AND productID=?';
                    $resultCount = $this->dbca->stmt_query( $sqlCount , 'iii' , array($startID,$endID,$productID) );

                    $sql = 'SELECT cardID FROM card_detail WHERE cardID BETWEEN ? AND ? AND cardStatus=3 AND productID=?';
                    $result = $this->dbca->stmt_query( $sql , 'iii' , array($startID,$endID,$productID) );

                    $count = $resultCount[0]->allCount;

                    if ( $count == 0 ){

                        if ($startID <= $_hiddEndID && $startID >= $_hiddStartID){

                            return array( 'code'=>400 , 'message'=>'该代金卡范围内以下卡号不能被申请:['.($_hiddEndID+1).']~['.$endID.']' );

                        }elseif ($endID >= $_hiddStartID && $endID <= $_hiddEndID){

                            return array( 'code'=>400 , 'message'=>'该代金卡范围内以下卡号不能被申请:['.$startID.']~['.($_hiddStartID-1).']' );

                        }elseif ($startID < $_hiddStartID && $endID >$_hiddEndID){

                            return array( 'code'=>400 , 'message'=>'该代金卡范围内以下卡号不能被申请:['.$startID.']~['.($_hiddStartID-1).']<br/>['.($_hiddEndID+1).']~['.$endID.']' );

                        }else {

                            return array( 'code'=>400 , 'message'=>'该代金卡范围内以下卡号不能被申请:['.$startID.']~['.$endID.']' );

                        }

                    }elseif( $count > 0) {

                        $per_arr = array();

                        foreach ($result as $value){
                            $per_arr[] = $value->cardID;
                        }

                        $old_arr = range($_hiddStartID, $_hiddEndID);
                        $new_arr = range($startID, $endID);

                        $str = '';

                        foreach ($new_arr as $new_value){
                            if (!in_array($new_value, $per_arr) && !in_array($new_value, $old_arr)){
                                $str .= '['.$new_value.']';
                            }
                        }

                        if(!empty($str)){

                            $arr = explode('][', $str);

                            if (count($arr) > 10){

                                $arr = array_slice($arr, 0, 9);
                                $str = implode('][', $arr);
                                $str .= ']......';
                                return array( 'code'=>400 , 'message'=>'该代金卡范围内以下卡号不能被申请:'.$str );

                            }else {

                                $str = implode('][', $arr);
                                $str .= ']';
                                return array( 'code'=>400 , 'message'=>'该代金卡范围内以下卡号不能被申请:'.$str );

                            }
                        }else {

//                            $this->returnBack($startID, $endID);
                            return array( 'code'=>200 , 'message'=>'此号段可以使用' , 'data'=>$arg_array );

                        }

                    }else{

                        return array( 'code'=>500 , 'message'=>'系统异常' );

                    }

                }

            }

        }

    }

    private function returnBack($_startID,$_endID){
        $sqlChange = 'UPDATE card_detail SET cardStatus=3 WHERE cardID BETWEEN ? AND ?';
        $typeChange = 'ii';
        $paramChange = array($_startID, $_endID);
        $this->dbca->stmt_query($sqlChange,$typeChange,$paramChange);
    }

    /**
     * 卡申领单发卡
     * @param int $applyID 申领单ID
     * @return array
     * @throws Exception
     */
    public function fkCardApply( $applyID ) {

        if( !is_numeric($applyID) )
            return array( 'code'=>400 , 'message'=>'参数错误，请与管理员联系' );

        //查询申领单信息
        $card_apply = new entity('card_apply');
        $card_apply->applyID = $applyID;

        if( !$this->dbca->fetch($card_apply) )
            return array( 'code'=>404 , 'message'=>'没有找到该申领单信息' );

        if( $card_apply->status != 1 )
            return array( 'code'=>400 , 'message'=>'该申领单已经发卡' );

        $card_apply->status = 2;

        //查询该申领单中的代金卡信息
        $search_card_detail = 'SELECT startID,endID,discount FROM card_apply_detail WHERE applyID=?';
        $applyInfo = $this->dbca->stmt_query($search_card_detail,'i',$applyID);

        if( empty($applyInfo) )
            return array( 'code'=>400 , 'message'=>'没有找到该申领单中代金卡信息' );

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //保存申领单主表信息
            $this->dbca->save( $card_apply );

            //更新该申领单中所有代金卡的状态为“已发卡”
            foreach($applyInfo as $info){

                $sql = 'UPDATE card_detail SET timeStamp=?,cardstatus=?,applyID=?,sendCardTime=?,discount=? WHERE cardID BETWEEN ? AND ?';
                $type = 'siisdii';
                $value = array(date('Y-m-d H:i:s'),5,$applyID,date('Y-m-d H:i:s'),$info->discount,$info->startID,$info->endID);
                $this->dbca->stmt_query($sql,$type,$value);

            }

            //提交事务
            $this->dbca->commit();

            return array( 'code'=>200 , 'message'=>'发卡成功' );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            error_log( $e->getMessage() );
            return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );

        }

    }

    /**
     * 删除卡申领单
     * @param $arg_array 申领单ID组成的数组，例如：
     * $arg_array = Array(
                            [0] => 19
                            [1] => 18
                            [2] => 17
                            ）
     * @return array
     * @throws Exception
     */
    public function delCardApply( $arg_array ) {

        /**
         * 代金卡状态：1.已生产  2.入库申请  3.已入库  4.申领申请  5.发卡  6.已使用  7.已作废
         */

        //统计不存在的申领单的数目
        $errorNum = 0;

        //统计已经发卡过的申领单数目
        $inStored = 0;

        //记录要删除的entity对象
        $deleteObjArr = array();

        if( empty($arg_array) )
            return array(  'code'=>400 , 'message'=>'请选择要删除的申领单' );

        //检查要删除的所有入库单
        foreach( $arg_array as $applyID ){

            //检查入库单信息是否存在
            $check_obj = new entity('card_apply');
            $check_obj->applyID = $applyID;

            if( !$this->dbca->fetch( $check_obj ) )
                $errorNum++;  //记录不存在的申领单数量

            if( $check_obj->status != 0 )
                $inStored++;  //记录已经发卡过的申领单数量

            $deleteObjArr[$applyID] = $check_obj;

        }

        if( $errorNum > 0 ){

            return array(  'code'=>400 , 'message'=>'所选部分信息已不存在，请刷新页面' );

        }

        if( $inStored > 0 ){

            return array(  'code'=>400 , 'message'=>'已发卡的申领单不可删除' );

        }


        try{

            //开启事务
            $this->dbca->beginTransaction();

            //循环删除
            foreach( $deleteObjArr as $applyID=>$delobj ){

                //删除申领单信息
                $this->dbca->delete( $delobj );

                //删除申领详情表中的数据
                $this->dbca->stmt_query('DELETE FROM card_apply_detail WHERE applyID = ?' , 'i' , $applyID);

                //将该入库单下的所有代金卡的状态重置为“已入库”
                $this->dbca->stmt_query( 'UPDATE card_detail SET applyID = ? ,cardStatus = ? WHERE applyID = ?' , 'sii' , array(NULL,3,$applyID) );

            }

            //提交事务
            $this->dbca->commit();

            return array('message'=>'删除成功', 'code'=>200);

        }catch( Exception $e ){

            //提交事务
            $this->dbca->rollBack();

            error_log($e->getMessage());
            return array('message'=>'系统错误，请与管理员联系', 'code'=>500);

        }

    }

    /**
     * 查询卡申领单详情表信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchCardApplyDetail( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //申领单号
        if ( isset($arg_array['applyID']) && is_numeric($arg_array['applyID']) ) {
            $sql .= ' AND applyID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['applyID'];
        }

        //卡面值
        if ( isset($arg_array['faceValue']) && is_numeric($arg_array['faceValue']) ) {
            $sql .= ' AND faceValue = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['faceValue'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_apply_detail ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询代金卡申领单详情信息
            $search_sql = 'SELECT * FROM card_apply_detail ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'uuid' => $item->uuid,
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'applyID' => $item->applyID,
                    'productID' => $item->productID,
                    'faceValue' => $item->faceValue,
                    'startID' => $item->startID,
                    'endID' => $item->endID,
                    'cardNumber' => $item->cardNumber,
                    'discount' => $item->discount,
                    'totalAmount' => $item->totalAmount,
                    'remark' => $item->remark
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }

    /**
     * 编辑代金卡申领单详情
     * @params $arg_array 参数数组
     */
    public function editCardApplyDetail( $arg_array ) {

        if( !isset($arg_array['uuid']) || empty($arg_array['uuid']) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        $oldStartID = $arg_array['hiddStartID'];  //原来的开始编号
        $oldEndID = $arg_array['hiddEndID'];     //原来的结束编号
        $startID = $arg_array['startID'];        //改变后的开始编号
        $endID = $arg_array['endID'];            //改变后的结束编号
        $applyID = $arg_array['applyID'];

        //检查参数
        if( empty($oldStartID) || empty($oldEndID) || empty($startID) || empty($endID) || empty($applyID) )
            return array( 'code'=>400 , 'message'=>'参数错误，缺少参数' );

        //连接错误提示信息
        $error_msg = '';

        if( !is_numeric($startID) )
            $error_msg .= '开始编号必须为数字<br>';

        if( !is_numeric($endID) )
            $error_msg .= '结束编号必须为数字<br>';

        if( $startID > $endID )
            $error_msg .= '开始编号不能大于结束编号<br>';

        if( !is_numeric($arg_array['cardNumber']) )
            $error_msg .= '卡数量必须为数字<br>';

        if( !is_numeric($arg_array['discount']) ){
            $error_msg .= '折扣必须为数字<br>';
        }else{

            if( $arg_array['discount'] <=0 || $arg_array['discount'] > 1 )
                $error_msg .= '折扣为不大于1的小数<br>';

        }

        if( !is_numeric($arg_array['totalAmount']) )
            $error_msg .= '总金额必须为数字<br>';

        if( $error_msg != '' )
            return array( 'code'=>400 , 'message'=>$error_msg );

        //查询对应的申领单详情信息
        $applyDetail = new entity('card_apply_detail');
        $applyDetail->uuid = $arg_array['uuid'];
        $applyDetail->applyID = $applyID;

        if( !$this->dbca->fetch($applyDetail) )
            return array( 'code'=>404 , 'message'=>'没有找到信息' );

        $applyDetail->faceValue = $arg_array['faceValue'];
        $applyDetail->startID = $startID;
        $applyDetail->endID = $endID;
        $applyDetail->cardNumber = $arg_array['cardNumber'];
        $applyDetail->totalAmount = $arg_array['totalAmount'];
        $applyDetail->discount = $arg_array['discount'];

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //先将原来起止编号下的代金卡“申领单号”字段置空
            $update_old_apply = 'UPDATE card_detail SET cardStatus = ?,applyID = ? WHERE cardID BETWEEN  ? AND ? AND applyID = ?';
            $this->dbca->stmt_query( $update_old_apply , 'iiiii' , array(3,NULL,$oldStartID,$oldEndID,$applyID) );

            //更新申领单详情
            $this->dbca->save( $applyDetail );

            //更新变更后的起止编号下的代金卡
            $update_new_apply = 'UPDATE card_detail SET cardStatus = ? , applyID = ? WHERE cardID BETWEEN  ? AND ?';
            $this->dbca->stmt_query( $update_new_apply , 'iiii' , array(4,$applyID,$startID,$endID) );

            //提交事务
            $this->dbca->commit();

            return array( 'code'=>200 , 'message'=>'更新成功' );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            error_log( $e->getMessage() );
            return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );
        }


    }

    /**
     * 删除卡申领单详情
     * $uuid为空时删除该申领单下所有详情数据
     * $uuid不为空时只删除该条数据
     * @param int $applyID 申领单ID
     * @param string $uuid UUID【默认为空】【uuid是申领单详情表的主键】
     * @return array
     * @throws Exception
     */
    public function delCardApplyDetail( $applyID, $uuid=null ) {

    }

    /**
     * 查询卡回款单信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchCardHK( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //回款单号
        if ( isset($arg_array['hkID']) && is_numeric($arg_array['hkID']) ) {
            $sql .= ' AND hkID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['hkID'];
        }

        //申领单号
        if ( isset($arg_array['applyID']) && is_numeric($arg_array['applyID']) ) {
            $sql .= ' AND applyID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['applyID'];
        }

        //回款方式
        if ( isset($arg_array['hkType']) && !empty($arg_array['hkType']) ) {
            $sql .= ' AND hkType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['hkType'];
        }

        //回款状态
        if ( isset($arg_array['status']) && in_array( $arg_array['status'] , array(0,1) ) ) {
            $sql .= ' AND status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['status'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_apply_huikuan ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询代金卡回款单信息
            $search_sql = 'SELECT * FROM card_apply_huikuan ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'hkID' => $item->hkID,
                    'applyID' => $item->applyID,
                    'hkType' => $item->hkType,
                    'hkAmount' => $item->hkAmount,
                    'hkTime' => $item->hkTime,
                    'hkPerson' => $item->hkPerson,
                    'status' => $item->status,
                    'externalNo' => $item->externalNo
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }

    /**
     * 新增或修改卡回款单
     * @param array $arg_array 回款单数组
     * @return array
     * @throws Exception
     */
    public function editCardHK( $arg_array ) {

        if(!isset($arg_array['hkType'],$arg_array['hkAmount'],$arg_array['applyID'],$arg_array['hkTime'],$arg_array['hkPerson'])){
           return array( 'code'=>400 , 'message'=>'参数错误' );
        }

        //连接错误信息
        $error_msg = '';

        $applyID = trim($arg_array['applyID']);
        if(empty($applyID))
            $error_msg .= '申领单号不能为空<br>';

        $hkType = trim($arg_array['hkType']);
        if(empty($hkType))
            $error_msg .= '回款方式不能为空<br>';

        $hkAmount = trim($arg_array['hkAmount']);
        if(empty($hkAmount) || !is_numeric($hkAmount))
            $error_msg .= '回款金额不能为空且必须为数字<br>';

        $hkPerson = trim($arg_array['hkPerson']);
        if(empty($hkPerson))
            $error_msg .= '回款人不能为空<br>';

        $hkTime = trim($arg_array['hkTime']);
        if(empty($hkTime))
            $error_msg .= '回款时间不能为空<br>';

        if( $error_msg != '' )
            return array( 'code'=>400 , 'message'=>$error_msg );

        $hkID = isset($arg_array['hkID']) ? trim($arg_array['hkID']) : null;

        //检查回款金额是否大于申领单总金额
        $sql = 'SELECT totalAmount FROM card_apply WHERE applyID=?';
        $applyInfo = $this->dbca->stmt_query($sql,'i',$applyID);
        if( empty($applyInfo) )
            return array( 'code'=>404 , 'message'=>'没有找到申领单信息' );

        //获取申领单卡总金额
        $total = $applyInfo[0]->totalAmount;

        //查询已经回款的金额
        if(isset($arg_array['hkID']) && !empty($arg_array['hkID'])){

            $hkID = trim($arg_array['hkID']);
            $sql = 'SELECT SUM(hkAmount) sectionTotal FROM card_apply_huikuan WHERE applyID = ? AND hkID != ?';
            $sectionInfo = $this->dbca->stmt_query($sql,'ii',$applyID,$hkID);

        }else{

            $sql = 'SELECT SUM(hkAmount) sectionTotal FROM card_apply_huikuan WHERE applyID=?';
            $sectionInfo = $this->dbca->stmt_query($sql,'i',$applyID);

        }

        if( empty($sectionInfo) ){
            $sectionTotal = 0;
        }else{
            $sectionTotal = $sectionInfo[0]->sectionTotal;
        }

        //计算新增此次回款金额后是否大于申领单总金额
        $totalSection = $hkAmount + $sectionTotal;

        if( $totalSection > $total ){
            $leftAmount = number_format(($totalSection-$total),2,'.','');
            return array( 'code'=>400 , 'message'=>'回款金额不能大于申领单总金额,多出回款金额为：'."<font color='red'>".$leftAmount."</font>元" );
        }

        try{

            $card_back_section = new entity('card_apply_huikuan');

            if( $hkID ){

                $card_back_section->hkID = $hkID;

                if( !$this->dbca->fetch($card_back_section) )
                    throw new Exception( '没有找到回款单信息' , 404 );

                if( $card_back_section->status == 1 )
                    throw new Exception( '该回款单已回款，不可修改' , 404 );

            }else{
                $card_back_section->creator = $arg_array['operator'];
            }

            $card_back_section->applyID = $applyID;
            $card_back_section->hkType = $hkType;
            $card_back_section->hkAmount = $hkAmount;
            $card_back_section->hkTime = $hkTime;
            $card_back_section->hkPerson = $hkPerson;
            $card_back_section->status = 0;
            $card_back_section->externalNo = isset($arg_array['externalNo'])?$arg_array['externalNo']:NULL;

            $this->dbca->save($card_back_section);

            if( $hkID ){
                return array( 'code'=>200 , 'message'=>'更新回款成功' );
            }else{
                return array( 'code'=>200 , 'message'=>'添加回款成功' );
            }

        }catch (Exception $e){

            if( $e->getCode() > 0 ){
                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );
            }else{
                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );
            }

        }

    }

    /**
     * 审核卡回款单
     * @param int $hkID 回款单ID
     * @return array
     * @throws Exception
     */
    public function auditCardHK( $hkID , $applyID) {


        if(empty($applyID) || empty($hkID) ){
            return array( 'code'=>400  , 'message'=>'参数错误，请与管理员联系');
        }

        //查询该回款单号的信息
        $sectionInfo = new entity('card_apply_huikuan');
        $sectionInfo->hkID = $hkID;
        $sectionInfo->applyID = $applyID;

        if( !$this->dbca->fetch($sectionInfo) )
            return array( 'code'=>400  , 'message'=>'记录不存在或已删除');

        if( $sectionInfo->status == 1 )
            return array( 'code'=>400  , 'message'=>'该回款单已经回款,请刷新页面');

        $sectionInfo->status = 1;

        try{
            //事务开启
            $this->dbca->beginTransaction();

            //更新回款单号状态
            $this->dbca->save( $sectionInfo );

            $sql = 'select totalAmount from card_apply where applyID=? and status=2';
            $applyInfo = $this->dbca->stmt_query($sql,'i',$applyID);
            if(!$applyInfo){
                throw new Exception( '没有找到申领单信息' , 404 );
            }
            $applyAmount = $applyInfo[0]->totalAmount;  //该申领单申领代金卡的总金额

            //查询该申领单已经回款的总金额
            $sql = 'SELECT sum(hkAmount) sectionTotal FROM card_apply_huikuan WHERE applyID=? AND status=1';
            $sectionInfo = $this->dbca->stmt_query($sql,'i',$applyID);

            $sectionTotal = $sectionInfo[0]->sectionTotal;

            /**
             * 该申领单已经回款的总金额同申请单总金额做对比，若相等，则更新申请单状态为“已回款”
             */
            if($sectionTotal == $applyAmount){//更新申请单状态
                $sql = 'UPDATE card_apply SET status=3,timeStamp=? WHERE applyID=? AND status=2';
                $this->dbca->stmt_query( $sql , 'si' , date('Y-m-d H:i:s') , $applyID );
            }

            //提交事务
            $this->dbca->commit();

            return array('code'=>200 , 'message'=>'回款成功');

        }catch(Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){
                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );
            }else{
                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );
            }

        }

    }

    /**
     * 删除卡回款单
     * @param array $arg_array 回款单ID组成的数组，例如：
     * $arg_array = array(
                    [0]=>1,
                    [1]=>2,
                   [2]=>3
                    ...
     * )
     * @return array
     * @throws Exception
     */
    public function delCardHK( $arg_array ) {

        //统计不存在的信息的数目
        $errorNum = 0;

        //统计已经回款过的回款单数目
        $sectionAudited = 0;

        //记录要删除的entity对象
        $deleteObjArr = array();

        if( empty($arg_array) )
            return array(  'code'=>400 , 'message'=>'请选择要删除的回款单' );

        //检查要删除的所有回款单
        foreach( $arg_array as $hkID ){

            //检查回款单信息是否存在
            $check_obj = new entity('card_apply_huikuan');
            $check_obj->hkID = $hkID;

            if( !$this->dbca->fetch( $check_obj ) )
                $errorNum++;  //记录不存在的回款单数量

            if( $check_obj->status == 1 )
                $sectionAudited++;  //记录已经回款过的回款单数量

            $deleteObjArr[] = $check_obj;

        }

        if( $errorNum > 0 ){

            return array(  'code'=>400 , 'message'=>'所选部分信息已不存在，请刷新页面' );

        }

        if( $sectionAudited > 0 ){

            return array(  'code'=>400 , 'message'=>'已回款的回款单不可删除' );

        }


        try{

            //开启事务
            $this->dbca->beginTransaction();

            //循环删除
            foreach( $deleteObjArr as $delobj ){

                $this->dbca->delete( $delobj );

            }

            //提交事务
            $this->dbca->commit();

            return array('message'=>'删除成功', 'code'=>200);

        }catch( Exception $e ){

            //提交事务
            $this->dbca->rollBack();

            error_log($e->getMessage());
            return array('message'=>'系统错误，请与管理员联系', 'code'=>500);

        }

    }

    /**
     * 查询卡申领单开票信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchCardInvoice( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //发票号
        if ( isset($arg_array['invoiceNo']) && is_numeric($arg_array['invoiceNo']) ) {
            $sql .= ' AND invoiceNo = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['invoiceNo'];
        }

        //申领单号
        if ( isset($arg_array['applyID']) && is_numeric($arg_array['applyID']) ) {
            $sql .= ' AND applyID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['applyID'];
        }

        //发票状态
        if ( isset($arg_array['status']) && in_array( $arg_array['status'] , array(0,1) ) ) {
            $sql .= ' AND status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['status'];
        }

        //冲红状态
        if ( isset($arg_array['rcwflg']) && in_array( $arg_array['rcwflg'] , array(0,1) ) ) {
            $sql .= ' AND rcwflg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['rcwflg'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_apply_invoice ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询代金卡发票信息
            $search_sql = 'SELECT * FROM card_apply_invoice ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'invoiceID' => $item->invoiceID,
                    'invoiceNo' => $item->invoiceNo,
                    'applyID' => $item->applyID,
                    'invoiceTitle' => $item->invoiceTitle,
                    'invoiceAmount' => $item->invoiceAmount,
                    'invoiceContent' => $item->invoiceContent,
                    'invoiceAvg' => $item->invoiceAvg,
                    'invoiceNum' => $item->invoiceNum,
                    'invoiceTime' => $item->invoiceTime,
                    'status' => $item->status,
                    'rcwflg' => $item->rcwflg
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }

    /**
     * 新增或修改卡申领单开票信息
     * @param array $arg_array 申领单开票信息数组
     * @return array
     * @throws Exception
     */
    public function editCardInvoice( $arg_array ) {

        if(!isset($arg_array['applyID'],$arg_array['invoiceTitle'],$arg_array['invoiceNo'],$arg_array['invoiceContent'],$arg_array['invoiceTime'],$arg_array['invoiceAvg'],$arg_array['invoiceNum'],$arg_array['invoiceAmount'])){
            return array( 'code'=>400 , 'message'=>'参数错误' );
        }

        if( empty( $arg_array['applyID'] ) )
            return array( 'code'=>400 , 'message'=>'参数错误,缺少参数' );

        //接收参数
        $applyID = trim($arg_array['applyID']);
        $invoiceTitle = trim($arg_array['invoiceTitle']);
        $invoiceNo = trim($arg_array['invoiceNo']);
        $invoiceContent = trim($arg_array['invoiceContent']);
        $invoiceTime = trim($arg_array['invoiceTime']);
        $invoiceAvg = trim($arg_array['invoiceAvg']);
        $invoiceNum = trim($arg_array['invoiceNum']);
        $invoiceAmount = trim($arg_array['invoiceAmount']);
        $invoiceID = isset( $arg_array['invoiceID'] )? $arg_array['invoiceID'] : NULL;

        //实例化公共类
        $commHandler = new commHandler( $this->dbca );

        //连接错误信息
        $error_msg = '';

        if(empty($invoiceTitle))
            $error_msg .= '发票抬头不能为空<br>';

        if( empty($invoiceNo) )
            $error_msg .= '发票单号不能为空<br>';

        if(empty($invoiceContent))
            $error_msg .= '发票内容不能为空<br>';

        if(empty($invoiceTime))
            $error_msg .= '开票日期不能为空<br>';

        if(empty($invoiceAvg)){
            $error_msg .= '发票单价不能为空<br>';
        }else{

            if( !$commHandler->isMoney($invoiceAvg) )
                $error_msg .= '发票单价格式有误<br>';

        }

        if(empty($invoiceNum)){
            $error_msg .= '发票数量不能为空<br>';
        }else{

            if(!is_numeric($invoiceNum))
                $error_msg .= '发票数量必须为数字<br>';

        }

        if(empty($invoiceAmount)){
            $error_msg .= '开票金额不能为空<br>';
        }else{

            if( !$commHandler->isMoney($invoiceAmount) )
                $error_msg .= '开票金额格式有误<br>';

        }

        if( $error_msg != '' )
            return array( 'code'=>400 , 'message'=>$error_msg );

        //查询申领单中的申领总金额
        $search_totalAmount_sql = 'SELECT totalAmount FROM card_apply WHERE applyID=?';
        $applyInfo = $this->dbca->stmt_query( $search_totalAmount_sql , 'i' , $applyID );

        if( empty($applyInfo) )
            return array( 'code'=>404 , 'message'=>'没有找到申领单号['.$applyID.']的申领信息' );

        //申领单总金额
        $totalAmount = $applyInfo[0]->totalAmount;

        //统计已开票的数据
        if( !empty( $invoiceID ) ){

            $search_invoiceTotalAmount = 'SELECT SUM(invoiceAmount) AS invoiceTotal FROM card_apply_invoice WHERE applyID=? AND invoiceID !=?';
            $invoiceInfo = $this->dbca->stmt_query( $search_invoiceTotalAmount , 'ii' , array($applyID , $invoiceID) );

        }else{

            $search_invoiceTotalAmount = 'SELECT SUM(invoiceAmount) AS invoiceTotal FROM card_apply_invoice WHERE applyID=?';
            $invoiceInfo = $this->dbca->stmt_query( $search_invoiceTotalAmount , 'i' , $applyID );

        }


        if(!$invoiceInfo){
            $invoiceTotal = 0;
        }else{
            $invoiceTotal = $invoiceInfo[0]->invoiceTotal;
        }

        //计算添加本次开票金额后，是否大于申领总金额
        $totalInvoice = $invoiceTotal+$invoiceAmount;

        if( $totalAmount < $totalInvoice ){

            $leftAmount = number_format(($totalInvoice-$totalAmount),2,'.','');
            return array( 'code'=>400 , 'message'=>'开票总金额已大于申请单总金额,多出金额为：<font color="red">' . $leftAmount .'</font>&nbsp;元' );

        }


        $card_invoice = new entity('card_apply_invoice');

        try{

            if( $invoiceID ){

                $card_invoice->invoiceID = $invoiceID;

                if( !$this->dbca->fetch( $card_invoice ) )
                    throw new Exception( '没有找到此发票信息' , 404 );

                if( $card_invoice->status == 1 )
                    throw new Exception( '该发票已开票，不可修改' , 400 );

            }else{

                $card_invoice->creator = $arg_array['operator'];

            }

            $card_invoice->applyID = $applyID;
            $card_invoice->invoiceNo = $invoiceNo;
            $card_invoice->invoiceTitle = $invoiceTitle;
            $card_invoice->invoiceAmount = $invoiceAmount;
            $card_invoice->invoiceContent = $invoiceContent;
            $card_invoice->invoiceAvg = $invoiceAvg;
            $card_invoice->invoiceNum = $invoiceNum;
            $card_invoice->invoiceTime  = $invoiceTime;
            $card_invoice->status  = 0;
            $card_invoice->rcwflg  = 0;
            $this->dbca->save($card_invoice);

           if( $invoiceID ){
               return array( 'code'=>200 , 'message'=>'发票更新成功' );
           }else{
               return array( 'code'=>200 , 'message'=>'发票新增成功' );
           }

        }catch (Exception $e){

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            }else{

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );

            }

        }

    }

    /**
     * 审核卡申领单开票信息
     * @param string $invoiceID //发票ID
     * $applyID  //申请单号
     * @return array
     * @throws Exception
     */
    public function auditCardInvoice( $invoiceID , $applyID ) {

        if( empty( $invoiceID ) || empty( $applyID ) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        //查询发票信息
        $apply_invoice = new entity('card_apply_invoice');
        $apply_invoice->invoiceID = $invoiceID;
        $apply_invoice->applyID = $applyID;

        if( !$this->dbca->fetch($apply_invoice) )
            return array( 'code'=>400 , 'message'=>'没有找到该发票信息' );

        if( $apply_invoice->status == 1 )
            return array( 'code'=>400 , 'message'=>'该发票已经开票' );

        $apply_invoice->status = 1;

        //记录此次开票的金额，用作参数返回
        $invoiceAmount = $apply_invoice->invoiceAmount;

        try{

            //更新发票状态
            $this->dbca->save( $apply_invoice );

            return array( 'code'=>200 , 'message'=>'开票成功' , 'data'=>$invoiceAmount );

        }catch(Exception $e){

            error_log( $e->getMessage() );
            return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );

        }

    }

    /**
     * 删除卡申领单开票信息
     * @param array $arg_array 发票ID组成的数组，例如：
     * $arg_array = array(
                        [0]=>1,
                        [1]=>2,
                        [2]=>2
                        ... ...
                         )
     * @return array
     * @throws Exception
     */
    public function delCardInvoice( $arg_array ) {

        //统计不存在的信息的数目
        $errorNum = 0;

        //统计已经开票过的发票单数目
        $invoiceAudited = 0;

        //统计已经冲红的发票
        $invoiceRCW = 0;

        //记录要删除的entity对象
        $deleteObjArr = array();

        if( empty($arg_array) )
            return array(  'code'=>400 , 'message'=>'请选择要删除的发票' );

        //检查要删除的所有发票
        foreach( $arg_array as $invoiceID ){

            //检查回款单信息是否存在
            $check_obj = new entity('card_apply_invoice');
            $check_obj->invoiceID = $invoiceID;

            if( !$this->dbca->fetch( $check_obj ) )
                $errorNum++;  //记录不存在的发票单数量

            if( $check_obj->status == 1 )
                $invoiceAudited++;  //记录已经开票过的发票单数量

            if( $check_obj->rcwflg == 1 )
                $invoiceRCW++;  //记录已经冲红的发票单数量

            $deleteObjArr[] = $check_obj;

        }

        if( $errorNum > 0 ){

            return array(  'code'=>400 , 'message'=>'所选部分信息已不存在，请刷新页面' );

        }

        if( $invoiceAudited > 0 ){

            return array(  'code'=>400 , 'message'=>'已开票的发票不可删除' );

        }

        if( $invoiceRCW > 0 ){

            return array(  'code'=>400 , 'message'=>'已冲红的发票不可删除' );

        }


        try{

            //开启事务
            $this->dbca->beginTransaction();

            //循环删除
            foreach( $deleteObjArr as $delobj ){

                $this->dbca->delete( $delobj );

            }

            //提交事务
            $this->dbca->commit();

            return array('message'=>'删除成功', 'code'=>200);

        }catch( Exception $e ){

            //提交事务
            $this->dbca->rollBack();

            error_log($e->getMessage());
            return array('message'=>'系统错误，请与管理员联系', 'code'=>500);

        }

    }

    /**
     * 卡申领单开票信息 -- 冲红
     * @param string $invoiceID 发票ID
     * @return array
     * @throws Exception
     */
    public function chCardInvoice( $invoiceID ) {

        if( empty( $invoiceID ) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        //查询发票信息
        $invoiceInfo = new entity('card_apply_invoice');
        $invoiceInfo->invoiceID = $invoiceID;

        if( !$this->dbca->fetch($invoiceInfo) )
            return array( 'code'=>400 , 'message'=>'没有找到该发票信息' );

        if( $invoiceInfo->rcwflg == 1 )
            return array( 'code'=>400 , 'message'=>'该发票已经冲红' );

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //生成一条冲红数据
            $card_invoice = new entity('card_apply_invoice');
            $card_invoice->applyID = $invoiceInfo->applyID;
            $card_invoice->invoiceNo = $invoiceInfo->invoiceNo;
            $card_invoice->invoiceTitle = $invoiceInfo->invoiceTitle;
            $card_invoice->invoiceContent = $invoiceInfo->invoiceContent;
            $card_invoice->invoiceAvg = $invoiceInfo->invoiceAvg*(-1);
            $card_invoice->invoiceNum = $invoiceInfo->invoiceNum;
            $card_invoice->invoiceAmount = $invoiceInfo->invoiceAmount*(-1);
            $card_invoice->invoiceTime  = $invoiceInfo->invoiceTime;
            $card_invoice->status  = 1;
            $card_invoice->rcwflg  = 1;
            $this->dbca->save($card_invoice);

            //记录冲红金额用作参数返回
            $invoiceAmount = $invoiceInfo->invoiceAmount;

            //更新原来的数据状态为“冲红”
            $invoiceInfo->rcwflg = 1;
            $this->dbca->save( $invoiceInfo );

            //提交事务
            $this->dbca->commit();

            return array( 'code'=>200 , 'message'=>'冲红成功' , 'data'=>$invoiceAmount );

        }catch(Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );
        }

    }

    /**
     * 修改卡系统卡状态(回滚代金卡状态)
     * @param int $cardID 卡号
     * @return array
     * @throws Exception
     */
    public function changeCardStat( $cardID ) {

        if( empty( $cardID ) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        //查询卡号信息
        $cardInfo = new entity('card_detail');
        $cardInfo->cardID = $cardID;

        if( !$this->dbca->fetch($cardInfo) )
            return array( 'code'=>404 , 'message'=>'没有找到卡号['.$cardID.']代金卡信息' );

        if( $cardInfo->cardStatus == 7 )
            return array( 'code'=>404 , 'message'=>'卡号['.$cardID.']代金卡已作废' );

        if( $cardInfo->cardStatus != 6 )
            return array( 'code'=>404 , 'message'=>'卡号['.$cardID.']代金卡还未使用' );

        try{

            //回滚卡信息
            $cardInfo->cardStatus = 5;
            $cardInfo->usedNumber = 0;
            $this->dbca->save( $cardInfo );

            return array( 'code'=> 200 , 'message' => '回滚成功' );

        }catch(Exception $e){

            error_log( $e->getMessage() );
            return array( 'code'=> 500 , 'message' => '系统错误，操作失败' );

        }

    }

    /**
     * 批量作废代金卡
     * @param array $card_array 卡号数组
     * $card_array = array(
     *      0 => '卡号',
     *      1 => '卡号',
     *      ...
     * );
     * @return array
     * @throws Exception
     */
    public function batchChangeCardStat( $card_array ) {

        //统计不存在的卡的数目
        $errorNum= 0;

        //统计已经作废的代金卡
        $canceledNum = 0;

        if( empty($card_array) )
            return array( 'code'=>400 , 'message'=>'请选择要禁用的代金卡' );

        //检查要删除的仓库是否全部存在
        foreach( $card_array as $cardID ){

            //检查卡号否存在
            $check_obj = new entity('card_detail');
            $check_obj->cardID = $cardID;

            if( !$this->dbca->fetch($check_obj) )
                $errorNum++;

            if( $check_obj->cardStatus == 7 )
                $canceledNum++;

        }

        if( $errorNum > 0 ){

            return array('message'=>'所选部分代金卡已不存在，请刷新页面' , 'code'=>400 );

        }

        if( $canceledNum > 0 ){

            return array('message'=>'所选部分代金卡已经作废，请刷新页面' , 'code'=>400 );

        }

        try{

            //将代金卡作废
            $update_SQL = 'UPDATE card_detail SET cardStatus = ?,timeStamp=? WHERE cardID IN (' . implode( ',' , $card_array ) . ')';

            $this->dbca->stmt_query( $update_SQL , 'is' , array(7,date("Y-m-d H:i:s")) );

            return array('message'=>'作废成功', 'code'=>200);

        }catch( Exception $e ){

            error_log($e->getMessage());
            return array('message'=>'系统错误，请与管理员联系', 'code'=>500);

        }

    }

}